package cn.tjd.smart_health.provider.service;

import cn.tjd.smart_health.api.SetMealService;
import cn.tjd.smart_health.common.entity.Setmeal;
import cn.tjd.smart_health.common.pojo.PageSelect;
import cn.tjd.smart_health.common.util.QiNiuUtils;
import cn.tjd.smart_health.provider.mapper.SetMealMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.UUID;

@DubboService
public class SetMealServiceImpl implements SetMealService {

    @Autowired
    private SetMealMapper setmealMapper;

    @Override
    public String uploadImg(byte[] file , String  fileName) {
        assert fileName != null;
        String suffix = fileName.substring(fileName.lastIndexOf('.'));
        fileName = UUID.randomUUID().toString() + suffix;
        QiNiuUtils.upload2Qiniu(file,fileName);
        return fileName;
    }

    @Override
    public PageSelect<Setmeal> findPage(Integer currentPage, Integer pageSize, String queryString) {

        Page<Setmeal> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<Setmeal>();

        queryWrapper.like(queryString != null , Setmeal::getCode,queryString)
                .or().like(queryString != null , Setmeal::getName,queryString)
                .or().like(queryString != null , Setmeal::getHelpCode,queryString);

        setmealMapper.selectPage(page, queryWrapper);

        PageSelect<Setmeal> pageSelect = new PageSelect<>();
        pageSelect.setRows(page.getRecords());
        pageSelect.setTotal(page.getTotal());
        return pageSelect;

    }

    @Override
    public Integer saveSetMeal(Setmeal setmeal, Integer[] checkGroups) {
       Integer result = setmealMapper.insert(setmeal);
        for (Integer id : checkGroups) {
            setmealMapper.InsertSetMealAndCheckGroup(setmeal.getId(),id);
        }
        return result;
    }

    @Override
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setmealMapper.selectById(id);
        return setmeal;
    }

    @Override
    public List<Integer> findCheckgroupIdsByMealId(Integer id) {
        return setmealMapper.findCheckGroupsBySetMeal(id);
    }

    @Override
    public Integer editSetMeal(Setmeal setmeal, Integer[] checkGroups) {

        Integer result = setmealMapper.updateById(setmeal);
        setmealMapper.deleteCheckGroupsBySetMealId(setmeal.getId());
        for (Integer id : checkGroups) {
           setmealMapper.InsertSetMealAndCheckGroup(setmeal.getId(),id);
        }
        return result;

    }

    @Override
    public Integer deleteSetMeal(Integer setmeal) {
        Integer result = setmealMapper.deleteById(setmeal);
        setmealMapper.deleteCheckGroupsBySetMealId(setmeal);
        return result;
    }
}
